<?php

class BillDetailController extends BackendApplicationController {

	public $layout = 'application.modules.bill.views.layouts.global';
	public function init()
	{
		Yii::app()->getClientScript()->registerCoreScript( 'jquery.ui' );
		Yii::app()->clientScript->registerCssFile(
		Yii::app()->clientScript->getCoreScriptUrl().
		'/jui/css/base/jquery-ui.css'
				);
				parent::init();
	}
	public function actionView($id) {
		$this->render('view', array(
			'model' => $this->loadModel($id, 'BackendBillDetailModel'),
		));
	}

	public function actionCreate() {
		$model = new BackendBillDetailModel;


		if (isset($_POST['BackendBillDetailModel'])) {
			$amBill = $_POST['BackendBillDetailModel']['am_bill'];
			$existsAmBill = Yii::app()->db->createCommand("select count(*) from bill where am_bill='$amBill'")->queryScalar();
			if($existsAmBill>0){
			$dateTime = Common::ConvertDatetime($_POST['BackendBillDetailModel']['created_datetime'], 'dd/mm/YY', true);
			$dateTime = $dateTime." {$_POST['hour']}:{$_POST['minute']}:{$_POST['secon']}";
			$model->setAttributes($_POST['BackendBillDetailModel']);
			$model->setAttribute('created_datetime', $dateTime);
			if ($model->save()) {
				if (Yii::app()->getRequest()->getIsAjaxRequest())
					Yii::app()->end();
				else
					$this->redirect(array('view', 'id' => $model->id));
			}
			}else{
				$model->addError("am_bill", "Mã Bill AM này không tồn tại.");
			}
		}

		$this->render('create', array( 'model' => $model));
	}

	public function actionUpdate($id) {
		$model = $this->loadModel($id, 'BackendBillDetailModel');


		if (isset($_POST['BackendBillDetailModel'])) {
			$dateTime = Common::ConvertDatetime($_POST['BackendBillDetailModel']['created_datetime']);
			$model->setAttributes($_POST['BackendBillDetailModel']);
			$model->setAttribute('created_datetime', $dateTime);
			if ($model->save()) {
				$this->redirect(array('view', 'id' => $model->id));
			}
		}

		$this->render('update', array(
				'model' => $model,
				));
	}

	public function actionDelete($id) {
		if (Yii::app()->getRequest()->getIsPostRequest()) {
			$this->loadModel($id, 'BackendBillDetailModel')->delete();

			if (!Yii::app()->getRequest()->getIsAjaxRequest())
				$this->redirect(array('admin'));
		} else
			throw new CHttpException(400, Yii::t('app', 'Your request is invalid.'));
	}

	public function actionIndex() {
		$dataProvider = new CActiveDataProvider('BackendBillDetailModel');
		$this->render('index', array(
			'dataProvider' => $dataProvider,
		));
	}

	public function actionAdmin() {
		$model = new BackendBillDetailModel('search');
		$model->unsetAttributes();

		if (isset($_GET['BackendBillDetailModel']))
			$model->setAttributes($_GET['BackendBillDetailModel']);

		$this->render('admin', array(
			'model' => $model,
		));
	}

}